<template>
	<div class="city-search">
		<input 
			type="text" 
			class="search-input" 
			placeholder="请输入城市名或拼音"
			v-model="keyword"
		>
		<div 
			class="search-content"
			ref="resultWrapper"
			v-show="keyword"
		>
			<ul class="search-result" >
				<li 
					class="result-item"
					v-for="item of list"
					:key="item.id"
					@click="cityClickHandle(item.name)"
				>
				{{item.name}}
				</li>
				<li class="result-item" v-show="hasNoData">没有找到匹配数据</li>
			</ul>
		</div>
	</div>
</template>

<script>
	import BScroll from 'better-scroll'
	export default {
		name:'citySearch',
		props: {
			cities:Object
		},
		data() {
			return {
				keyword:'',
				timer:null,
				list:[]
			}
		},
		computed: {
			hasNoData() {
				return !this.list.length;
			}
		},
		methods: {
			cityClickHandle(city) {
				this.$store.commit('changeCityState',city)
				/*跳转到首页*/
				this.$router.push('/');
			}
		},
		watch: {
			/*监听输入框的变化*/
			keyword() {
				/*关键字为空时将结果数组置空*/
				if(!this.keyword) {
					this.list=[];
					return;
				}
				/**
                 * 函数节流
                 * 优化性能
                 */
                if(this.timer) {
                    clearTimeout(this.timer);
                }
                this.timer=setTimeout(() => {
                	/*用于存放搜索结果*/
                   const result=[];
                   for(let i in this.cities) {
                   	this.cities[i].forEach((value) => {
                   		if(value.spell.indexOf(this.keyword)>-1 ||
                   			value.name.indexOf(this.keyword)>-1) {
                   			result.push(value)
                   		}
                   	})
                   }
                   this.list=result;
                },100)
			}
		},
		mounted() {
			/*使用better-scroll*/
			this.scroll=new BScroll(this.$refs.resultWrapper,{
				click:true
			});
		},

	}
</script>

<style lang="scss" scoped>
	@import 'styles/varible';
	.city-search {
		height: .74rem;
		padding: 0 .15rem;
		background-color: $bgColor;
		.search-input {
			box-sizing: border-box;
			height: .6rem;
			line-height: .6rem;
			border-radius:.15rem;
			padding: 0 .1rem;
			text-align: center;
			color:#666;
			width: 100%;
		}
		.search-content {
			z-index:99;
			overflow: hidden;
			position: absolute;
			top: 1.62rem;
			left: 0;
			right: 0;
			bottom: 0;
			background-color: #f5f5f5;
			.result-item {
				padding-left: .15rem;
				height: .64rem;
				line-height: .64rem;
				background: #fff;
				color: #666;
			}
		}
	}
</style>